import scrapy
import requests,json
from bid.items import BidItem
from bid.tools import *


class ShanxiSpider(scrapy.Spider):
    name = 'shanxi'
    allowed_domains = ['prec.sxzwfw.gov.cn/']
    start_urls = ['http://prec.sxzwfw.gov.cn/']
    url = 'http://prec.sxzwfw.gov.cn/jyxx/index_%s.jhtml'
    t_dic ={
        'jyxxzcgg':['政府采购-采购公告','1'],
        'jyxxzcgz':['政府采购-更正公告','2'],
        'jyxxzczb':['政府采购-中标结果','3'],
        'jyxxgczb':['工程建设-招标/资审公告','1'],
        'jyxxgcgz':['工程建设-更正公告','2'],
        'jyxxgchxr':['工程建设-中标候选人公示','2'],
        'jyxxgcgs':['工程建设-中标结果公示','3'],
        'jyxxgcyc':['工程建设-异常公告','2'],
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    msg =[]
    def start_requests(self):
        for page in range(1,999999):
            res = requests.get(url=self.url%page,headers=self.headers).text
            ls = re.findall('<a href="(http://prec.sxzwfw.gov.cn:80/.*?)" target="_blank" class="cs_two_c_2".*?class="cs_bz_cont">\s*(.*?)\s*</p>.*?class="cs_bz_cont_1_time">(.*?)<',res,re.S)
            last_page = int(re.findall(',count: (\d+)\s',res,re.S)[-1])//10
            if page > last_page:
                break
            for l in ls:
                item = {}
                item['link'] = l[0]
                key = item['link'].split('/')[-2]
                if key not in self.t_dic:
                    continue
                item['title'] = l[1]
                item['time'] = l[2].replace('/','-')
                item['classification'] = '山西-'+self.t_dic[key][0]
                item['typ']=self.t_dic[key][-1]
                if redis_dupefilter(item) or item['time'].startswith('2021'):
                    self.msg.append(page)
                    break
                yield scrapy.Request(url=item['link'], callback=self.parse, meta={'item': item})
            if page in self.msg:
                print('完成')
                break
            time.sleep(len(ls))

    def parse(self, response):
        item = BidItem()
        item.update(response.meta['item'])
        item['content'] = get_content(response.text, '//div[@class="div-article2"]')
        item = get_field(dict(item))
        yield item